<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel'
import { importEmployeeAPI } from '@/api/employees'
import { getImportJsData } from '@/utils/excel'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 解析前 这个函数会被自动调用 且在校验通过的时候返回true 不过返回false
    // 注意：只有校验通过之后才会正式进行解析的动作 否则直接停止 避免浪费
    beforeUpload(file) {
      // file：文件对象
      console.log(file)
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 解析成功之后的回调
    async handleSuccess({ results, header }) {
      // results: 表格body体形成的数据
      // header：表头部分形成参数
      // 1. 把插件解析之后的数据转化成接口要求的数据 [现成方法]
      this.tableData = results
      this.tableHeader = header
      const headerRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      const data = getImportJsData(results, headerRelation)
      console.log(data)
      const res = await importEmployeeAPI(data)
      this.$message.success(res.message)
      this.$router.back()
    }
  }
}
</script>
